package com.library.repository;

import com.library.entity.Favorite;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 收藏数据访问层接口
 */
@Repository
public interface FavoriteRepository extends JpaRepository<Favorite, Long> {
    /**
     * 根据用户ID查找收藏列表
     */
    @Query("SELECT f FROM Favorite f JOIN FETCH f.book JOIN FETCH f.user " +
           "WHERE f.user.id = :userId ORDER BY f.createdAt DESC")
    List<Favorite> findByUserIdOrderByCreatedAtDesc(@Param("userId") Long userId);

    /**
     * 根据用户ID和图书ID查找收藏
     */
    @Query("SELECT f FROM Favorite f JOIN FETCH f.book JOIN FETCH f.user " +
           "WHERE f.user.id = :userId AND f.book.id = :bookId")
    Optional<Favorite> findByUserIdAndBookId(@Param("userId") Long userId, @Param("bookId") Long bookId);

    /**
     * 检查用户是否已收藏某图书
     */
    boolean existsByUserIdAndBookId(Long userId, Long bookId);

    /**
     * 根据用户ID删除所有收藏
     *
     * @param userId 用户ID
     */
    void deleteByUserId(Long userId);
}

